import { NextRequest, NextResponse } from 'next/server'
import  prisma  from '@/lib/prisma'
import { getUserIdFromRequest } from '@/lib/authUtils'  // 使用正确的函数

// 创建课程小节（支持单个创建和批量创建）
export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
): Promise<NextResponse> {
  try {
    const userId = await getUserIdFromRequest(request)  // 使用返回 string | null 的函数
    if (!userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // 验证课程所有权
    const course = await prisma.vms_course.findFirst({
      where: {
        id: params.id,
        user_id: userId  // 不需要 .toString() 因为 userId 已经是 string
      }
    })

    if (!course) {
      return NextResponse.json({ error: 'Course not found' }, { status: 404 })
    }

    const body = await request.json()
    
    // 检查是批量创建还是单个创建
    if (body.copy_ids && Array.isArray(body.copy_ids)) {
      // 批量从文案创建课程小节
      const { copy_ids } = body

      // 获取文案列表
      const copies = await prisma.vms_copy.findMany({
        where: {
          id: { in: copy_ids },
          user_id: userId  // 这里也不需要类型转换
        },
        orderBy: {
          pxh: 'asc'
        }
      })

      // 获取当前最大顺序号
      const lastSection = await prisma.vms_course_section.findFirst({
        where: { course_id: params.id },
        orderBy: { order: 'desc' }
      })
      let currentOrder = (lastSection?.order || 0) + 1

      // 批量创建课程小节
      const sections = await Promise.all(
        copies.map(async (copy) => {
          const section = await prisma.vms_course_section.create({
            data: {
              course_id: params.id,
              title: copy.title || `第${currentOrder}节`,
              content:  copy.content || '',
              content_md: copy.rich_content || '',
              is_free: true,
              source_copy_id: copy.id,
              order: currentOrder++
            },
            include: {
              source_copy: true
            }
          })
          return section
        })
      )

      return NextResponse.json(sections)
    } else {
      // 单个创建课程小节
      const { title, content, source_copy_id, order } = body

      // 如果指定了来源文案，获取文案内容
      let sectionContent = content
      let sectionContent_md = ''
      if (source_copy_id && !content) {
        const sourceCopy = await prisma.vms_copy.findFirst({
          where: {
            id: source_copy_id,
            user_id: userId.toString()
          }
        })
        
        if (sourceCopy) {
          sectionContent = sourceCopy.content || ''
          sectionContent_md = sourceCopy.rich_content || ''
        }
      }

      // 如果没有指定顺序，自动设置为最后
      let sectionOrder = order
      if (!sectionOrder) {
        const lastSection = await prisma.vms_course_section.findFirst({
          where: { course_id: params.id },
          orderBy: { order: 'desc' }
        })
        sectionOrder = (lastSection?.order || 0) + 1
      }

      const section = await prisma.vms_course_section.create({
        data: {
          course_id: params.id,
          title,
          content: sectionContent,
          content_md: sectionContent_md,
          source_copy_id,
          is_free: true,
          order: sectionOrder
        },
        include: {
          source_copy: true
        }
      })

      return NextResponse.json(section)
    }
  } catch (error) {
    console.error('Error creating course section:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}